package public

import (
	"context"
	"errors"
	"time"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginUser) (resp *types.LoginResp, err error) {
	data := models.User{Username: req.Username}
	has := db.GetData(&data)
	if !has {
		return nil, errors.New("登录账号不存在或已删除")
	}
	if data.IsUse != 10 {
		return nil, errors.New("登录账号被禁用，请联系管理员")
	}
	if utils.MD5(utils.MD5(req.Password)+data.Salt) != data.Password {
		return nil, errors.New("登录密码不正确")
	}
	jwtUser := utils.JwtUser{}
	copier.Copy(&jwtUser, &data)
	resp = &types.LoginResp{}
	copier.Copy(resp, &data)
	accessToken, _ := utils.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, jwtUser)
	resp.AccessToken = accessToken
	resp.ExpiredAt = time.Now().Unix() + 60*60*24*7

	return resp, nil
}
